package com.king.login.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.king.login.dao.SystemUserMapper;
import com.king.login.entity.SystemUser;
import com.king.platform.redis.RedisUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
  @Resource
  private SystemUserMapper systemUserMapper;
  @Autowired
  private RedisUtils redisUtils;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SystemUser::getUserName, username);
    SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
    if (Objects.isNull(systemUser)) {
      throw new RuntimeException("用户名或者密码错误");
    }
    //存储用户id到redis
    redisUtils.set("user:" + systemUser.getId(), 60 * 60 * 1000);

    return new LoginUser(systemUser);
  }
}
